#include <REGX52.H>
#include <INTRINS.H>

sbit XPT2046_DIN = 	P3^4;
sbit XPT2046_CS = 	P3^5;
sbit XPT2046_DCLK = P3^6;
sbit XPT2046_DOUT = P3^7;

void Delay1ms()		//@11.0592MHz
{
	unsigned char i, j;

	_nop_();
	i = 2;
	j = 199;
	do
	{
		while (--j);
	} while (--i);
}

/**
  * @brief		XPT2046读取AD值
  * @parm		Command：命令字 范围：头文件宏定义
  * @retval		AD转换后的数值，8位数据/12位数据
  */
unsigned int XPT2046_ReadAD(unsigned char Command)
{
	unsigned int Data = 0;
	unsigned char i, Com = Command;
	XPT2046_DCLK = 0;
	XPT2046_CS = 0;
	//写命令
	for(i = 0; i < 8; ++i)
	{
		XPT2046_DIN = Com >> 7;
		Com = Com << 1;
		XPT2046_DCLK = 1;//上升沿写入
		XPT2046_DCLK = 0;
	}
	//读数据
	for(i = 0; i < 16; ++i)
	{
		XPT2046_DCLK = 1;
		XPT2046_DCLK = 0;//下降沿读出
		if(XPT2046_DOUT)
			Data |= (0x8000 >> i);
	}
	XPT2046_CS = 1;
	//根据命令字返回对应位数的AD值
	if(Command & 0x08)
		return Data >> 8;
	else
		return Data >> 4;
}